package com.test.multithread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.CountDownLatch;

/**
 * Created by jl on 2016/8/7.
 */
public class Demo2 {
    public static void main(String[] args) throws IOException, InterruptedException {
        int count = 3;
        CountDownLatch latch = new CountDownLatch(count);
        File file = new File("test2.txt");
//        conflictTest(file);
        RandomAccessFile[] rafArr = new RandomAccessFile[count];
        String[] contents = new String[]{"abc", "def", "ghi"};
        for (int i =0;i<count;i++) {
            rafArr[i] = new RandomAccessFile(file, "rw");
            new WriteThread(rafArr[i], latch, i * 3, contents[i]).start();
        }
        latch.await();
        System.out.println("end");
    }

    private static void conflictTest(File file) throws FileNotFoundException, InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        RandomAccessFile raf1 = new RandomAccessFile(file, "rw");
        RandomAccessFile raf2 = new RandomAccessFile(file, "rw");
        WriteThread thread1 = new WriteThread(raf1, latch, 0, "123");
        WriteThread thread2 = new WriteThread(raf2, latch, 1, "456");
        thread1.start();
        thread2.start();
        latch.await();
        System.out.println("finish");
    }
}
